package myProject.gwt.client.simpleTable;

import myProject.gwt.client.DebugPanel;

import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Widget;

public class StaticTable extends AbstractTable{

	private HTML table;
	private Header header;
	private IDataSource dataSource;

	
	public StaticTable(String[] headerCaptions, IDataSource dataSource){
		super();
		this.dataSource = dataSource;
		createHeader(headerCaptions);
		//init();
	}
	
	public void init(){
		super.init();
	}
	
	private void createHeader(String[] headerCaptions){
		
		header = new Header();
		for(int col=0; col < headerCaptions.length; col++){

			HeaderCell hc = new HeaderCell(col, headerCaptions[col]);
			hc.setWidth(100);
			header.addHeaderCell(hc);
		}
		
		header.setHeaderListener(new IHeaderListener(){
			@Override
			public void headerResized(IHeaderCell header) {
				resizeColumn(header.getColumnIndex(), getColumnWidth(header.getColumnIndex()));
			}

			@Override
			public void headerResizing(IHeaderCell cell) {
				// TODO Auto-generated method stub				
			}			
		});
	}
	
	@Override
	protected Widget getContent() {
		table = createVerySimpleTable();
		return table; 
	}

	@Override
	protected IHeader getHeader() {
		return header;
	}
	
	private void resizeColumn(int columnIndex, int width){
		Element el = DOM.getElementById("resizeCell"+columnIndex);
		el.getStyle().setPropertyPx("width", width);
	}
	
	private HTML createVerySimpleTable(){
		StringBuilder sb = new StringBuilder();
				
		sb.append("<table cellpading=\"0\" cellspacing=\"0\" style=\"table-layout:fixed;\" >");
		for(int row=-1; row<dataSource.getRecordCound(); row++){
			
			String style;
			if((row % 2) == 0) style = "evenRow";
			else style = "oddRow";		
			sb.append("<tr class=\""+style+"\">");

			for(int col=0; col<header.getHeaderCellCount(); col++){				
				
				//fake columns for resizing
				if(row == -1){
					sb.append("<td id=\"resizeCell"+col+"\" style=\"width: "+getColumnWidth(col)+"px;\">");	
					continue;
				}
				
				sb.append("<td>");
				
				String value = dataSource.getCellValue(col, row);
				sb.append(value);
			}
			sb.append("</tr>");
		}
		sb.append("</table>");
		return new HTML(sb.toString());
	}

}
